package com.sduept.nwld.dataserver.controller.rota;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.rota.HolidayManager;
import com.sduept.nwld.dataserver.manager.rota.RotaOrderManager;
import com.sduept.nwld.dataserver.manager.rota.RotaPersonManager;
import com.sduept.nwld.dataserver.model.rota.HolidayInfo;
import com.sduept.nwld.dataserver.model.rota.RotaOrder;
import com.sduept.nwld.dataserver.model.rota.RotaPerson;
import com.sduept.utils.DateUtil;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import java.util.*;

@Named
@ViewScoped
public class HolidayController extends AbstractController {

	private static final long serialVersionUID = -1705038961034875987L;

	@Autowired
	private HolidayManager holidayManager;
	@Autowired
	private RotaOrderManager rotaOrderManager;
	@Autowired
	private RotaPersonManager rotaPersonManager;
	private ScheduleModel eventModel;
	private ScheduleEvent event = new DefaultScheduleEvent();

	private HolidayInfo selectedHoliday = new HolidayInfo();
	private HolidayInfo holiday = new HolidayInfo();
	private List<HolidayInfo> holidays = new ArrayList<HolidayInfo>();
	private List<String> holidayNames = new ArrayList<String>();

	private List<HolidayInfo> selectDateHolidays = new ArrayList<HolidayInfo>();
	private HolidayInfo selectDateHoliday = new HolidayInfo();
	private List<RotaOrder> rotaOrders = new ArrayList<RotaOrder>();
    private RotaOrder rotaOrder = new RotaOrder();
	private List<RotaPerson> rotaPersons = new ArrayList<RotaPerson>();
    private RotaPerson rotaPerson = new RotaPerson();
    private RotaPerson selectRotaPerson = new RotaPerson();
    
	private String selectDate;	
	private String holidayName;
	private Date holidayStartDate;
	private Date holidayEndDate;
	private String holidayRemark;	
	private String rotaPersonIdAndName;

	@PostConstruct
	public void init() {
		initRotaOrder();
		initRotaPersons();
		eventModel = new DefaultScheduleModel();
		holidays = holidayManager.getAllHoliday();
		sortHolidays();
		for (HolidayInfo bean : holidays) {
			List<RotaPerson> rps=rotaPersonManager.findRotaPersonByRoteDate(bean.getHoliday());
			if(rps!=null && !rps.isEmpty()){
				RotaPerson rp=rps.get(0);
				eventModel.addEvent(new DefaultScheduleEvent(bean.getHolidayName()+" 值班人:"+rp.getPersonName(),addOneDay(bean.getHoliday()),addOneDay(bean.getHoliday())));
			}else{
				eventModel.addEvent(new DefaultScheduleEvent(bean.getHolidayName(),addOneDay(bean.getHoliday()),addOneDay(bean.getHoliday())));
			}
			getOrder(bean);
		}
	}

	//设置节日序号
	public void getOrder(HolidayInfo holidayInfo) {
		if(!(holidayNames.contains(holidayInfo.getHolidayName()))) {
			holidayNames.add(holidayInfo.getHolidayName());
		}
	}
	
	//解决schedule页面显示的节假日提前一天问题
	public Date addOneDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, 1);
		return DateUtil.getDateByString(DateUtil.getStringDate(cal.getTime(), DateUtil.pattern_ymd),DateUtil.pattern_ymd);
	}
	
	//解决schedule页面显示的节假日提前一天问题
	public Date minusOneDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, -1);
		return DateUtil.getDateByString(DateUtil.getStringDate(cal.getTime(), DateUtil.pattern_ymd),DateUtil.pattern_ymd);
	}
	
	public void onCellEdit(CellEditEvent event) {
		selectedHoliday = null;
        selectedHoliday = selectDateHolidays.get(event.getRowIndex());
        if(null != selectedHoliday) {
        	holidayManager.updateHolidayInfo(selectedHoliday);
        }
		addSuccessMessage("修改成功!");
   }
	
	public void preCreateHoliday() {
		holiday = new HolidayInfo();
	}

	public void editHoliday() {
		holiday = selectedHoliday;
	}

	public void updateHolidayInfo() {
		if (holiday != null) {
			holidays.set(holidays.indexOf(holiday), holiday);
			holiday = holidayManager.updateHolidayInfo(holiday);
			//selectedHoliday = new HolidayInfo();
		}
		sortHolidays();
	}
	public void saveHolidayInfo(){
		try{
			if (holidayName!= null && !"".equals(holidayName) && holidayStartDate!=null &&	holidayEndDate!=null) {// 新建
				if(holidayStartDate.getTime()>holidayEndDate.getTime()){
					addErrorMessage("结束日期不能小于开始日期");
				}else{
					List<Date> dates=Date_start_end(holidayStartDate,holidayEndDate);
					if(dates!=null && !dates.isEmpty()){
						for(Date date:dates){
							HolidayInfo _holiday=new HolidayInfo();
							_holiday.setId(ObjectId.get().toString());
							_holiday.setHoliday(date);
							_holiday.setHolidayName(holidayName);
							_holiday.setRemark(holidayRemark);
							setHolidayInfo(_holiday);
							holidayManager.createHolidayInfo(_holiday);
							holidays.add(_holiday);
						}
					}
					addSuccessMessage("节假日添加成功");
				}
			}else{
				addErrorMessage("节假日信息为空，保存失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			addErrorMessage("异常，节假日添加失败");
		}finally{
			holidayName="";
			holidayStartDate=null;
			holidayEndDate=null;
			holidayRemark="";
		}
	}
	
	
	/**
	 * 获取起止日期内的所有日期
	 * @param start_date
	 * @param end_date
	 * @return
	 */
	private List<Date> Date_start_end(Date start_date,  Date end_date){
		 List<Date> cals=new ArrayList<Date>();
		 try{
			   Calendar dayc1 = new GregorianCalendar();
			   Calendar dayc2 = new GregorianCalendar();
			   Date daystart =DateUtil.getDateByString(DateUtil.getStringDate(start_date , DateUtil.pattern_ymd) ,  DateUtil.pattern_ymd);//按照yyyy-MM-dd格式转换为日期
			   Date dayend =DateUtil.getDateByString(DateUtil.getStringDate(end_date , DateUtil.pattern_ymd) ,  DateUtil.pattern_ymd);//按照yyyy-MM-dd格式转换为日期
			   dayc1.setTime(daystart); //设置calendar的日期
			   dayc2.setTime(dayend);
			   for (; dayc1.compareTo(dayc2) <= 0;) {   //dayc1在dayc2之前就循环
				   cals.add(dayc1.getTime());
				   dayc1.add(Calendar.DAY_OF_YEAR, 1);  //加1天
			   }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return cals;
	}			
	public void setHolidayInfo(HolidayInfo holiday) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(holiday.getHoliday());
		holiday.setYear(cal.get(Calendar.YEAR));
		// 序号
		if(holidayNames.contains(holiday.getHolidayName())) {
			//如果当前节日名称已存在，则新的节日的序号为节日总数+1
			holiday.setSortOrder(holidayNames.indexOf(holiday.getHolidayName()) + 1);
		} else {
			holiday.setSortOrder(holidayNames.size()+1);
		}
	}
	
	public String formatterDate(Date date){
		return DateUtil.getStringDate(date, DateUtil.pattern_ymd);
	}
	
	private void sortHolidays() {
		// 重新排序
		Collections.sort(holidays, new Comparator<HolidayInfo>() {
			@Override
			public int compare(HolidayInfo h1, HolidayInfo h2) {
				return h1.getSortOrder() - h2.getSortOrder();
			}
		});
	}

	public void deleteHoliday() {
		if (selectedHoliday != null && !selectedHoliday.getId().isEmpty()) {
			holidayManager.delHolidayInfo(selectedHoliday.getId());
			holidays.remove(selectedHoliday);
			addSuccessMessage("删除成功！");
			selectedHoliday = new HolidayInfo();
		} else {
			addErrorMessage("请选择要删除的数据！");
		}
	}

	public Date getInitialDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);
		return calendar.getTime();
	}
	

	public ScheduleModel getEventModel() {
		return eventModel;
	}

	public ScheduleEvent getEvent() {
		return event;
	}

	public void setEvent(ScheduleEvent event) {
		this.event = event;
	}

	public void addEvent(ActionEvent actionEvent) {
		if (event.getId() == null) {
			eventModel.addEvent(event);
			saveEventHoliday(event);
		}
		else
			eventModel.updateEvent(event);

		event = new DefaultScheduleEvent();
	}
	
	//从schedule上直接添加节假日
	public void saveEventHoliday(ScheduleEvent event2) {
		holiday = new HolidayInfo();
		// 序号
		if(holidayNames.contains(event2.getTitle())) {
			//如果当前节日名称已存在，则新的节日的序号为节日总数+1
			holiday.setSortOrder(holidayNames.indexOf(holiday.getHolidayName()) + 1);
		} else {
			holiday.setSortOrder(holidayNames.size()+1);
		}
		//节日名称
		holiday.setHolidayName(event2.getTitle());
		// 年份
		Calendar cal = Calendar.getInstance();
		cal.setTime(event2.getStartDate());
		holiday.setYear(cal.get(Calendar.YEAR));
		//日期
		holiday.setHoliday(event2.getStartDate());
		//备注
		holiday.setRemark(event2.getDescription());
		holidayManager.createHolidayInfo(holiday);
		holidays.add(holiday);
		addSuccessMessage("保存成功");
	}

	public void onEventSelect(SelectEvent selectEvent) {
		try{
			event = (ScheduleEvent) selectEvent.getObject();
			String holidayName = event.getTitle();
			if(holidayName.split(" ").length==2){
				holidayName=holidayName.split(" ")[0];
			}
			//获得的日期减去一天
			selectDate = DateUtil.getStringDate(minusOneDay(event.getStartDate()), DateUtil.pattern_ymd);
			if(selectDate != null && !"".equals(selectDate)) {
				List<HolidayInfo> his=holidayManager.findHolidayInfoByHolidayNameAndDate(minusOneDay(event.getStartDate()), holidayName);
				if(his!=null  && !his.isEmpty())
					selectDateHoliday = his.get(0);			
				List<RotaPerson> rps = rotaPersonManager.findRotaPersonByRoteDate(minusOneDay(event.getStartDate()));
				if(rps!=null && !rps.isEmpty()){
					rotaPerson=rps.get(0);
					rotaPersonIdAndName = rotaPerson.getPersonId() + "-" + rotaPerson.getPersonName();
				}else{
					rotaPersonIdAndName="";
				}
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	public void onDateSelect(SelectEvent selectEvent) {
		event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(), (Date) selectEvent.getObject());
		selectDate = DateUtil.getStringDate((Date) selectEvent.getObject(), DateUtil.pattern_ymd);
		if(selectDate != null && !"".equals(selectDate)) {
			selectDateHolidays = holidayManager.findAllHolidayInfoByDate((Date)selectEvent.getObject());
		}
	}
	
	public void onEventMove(ScheduleEntryMoveEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event moved", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());
		addMessage(message);
	}

	public void onEventResize(ScheduleEntryResizeEvent event) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Event resized", "Day delta:" + event.getDayDelta()
						+ ", Minute delta:" + event.getMinuteDelta());
		addMessage(message);
	}

	private void addMessage(FacesMessage message) {
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void initRotaOrder() {
		rotaOrders = rotaOrderManager.findAllRotaOrder();
	}
	
	private void initRotaPersons() {
		rotaPersons=rotaPersonManager.findAllHolidayRotaPerson();
	}
	
	public void preCreateRotaPerson() {
		rotaPerson = new RotaPerson();
	}
	
	public void preEditRotaPerson() {
		rotaPerson = selectRotaPerson;
	}
	
	@SuppressWarnings("static-access")
	public void editRotaPerson() {
		try{
			if(rotaOrder!=null){
				if(selectDateHoliday.getHoliday() !=null){
					rotaPerson.setRotaDate(selectDateHoliday.getHoliday());
					Calendar cal=Calendar.getInstance();
					cal.setTime(selectDateHoliday.getHoliday());
					rotaPerson.setYear(cal.get(cal.YEAR));
					//+" 第"+(cal.get(Calendar.WEEK_OF_YEAR)+1)+"周周"+cal.get(cal.DAY_OF_WEEK)
					rotaPerson.setRemark(selectDateHoliday.getHolidayName());
				}else{
					addErrorMessage("未选择日期，保存失败");
					return;
				}
				rotaPerson.setPersonId(rotaPersonIdAndName.split("-")[0]);
				rotaPerson.setPersonName(rotaPersonIdAndName.split("-")[1]);
			}
			rotaPersonManager.updateRotaPerson(rotaPerson);
			selectRotaPerson = new RotaPerson();
			addSuccessMessage("节假日值班人员编辑成功!");
			init();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("static-access")
	public void saveRotaPerson() {
		if(rotaPerson != null) {			
			if(rotaPerson.getId() == null) {//新建
				if(rotaOrder!=null){
					if("".equals(rotaPerson.getRemark())||rotaPerson.getRemark()==null){
						addErrorMessage("未选择节假日，保存失败");
						return;
					}
					Calendar cal=Calendar.getInstance();
					if(rotaPerson.getRotaDate()!=null){
						cal.setTime(rotaPerson.getRotaDate());
						if(cal.get(cal.MONTH)==11 && "元旦".equals(rotaPerson.getRemark())){
							rotaPerson.setYear(cal.get(cal.YEAR)+1);
						}else{
							rotaPerson.setYear(cal.get(cal.YEAR));
						}
					}else{
						addErrorMessage("未选择日期，保存失败");
						return;
					}
					if(!"null-".equals(rotaOrder.toString())){
						rotaPerson.setPersonId(rotaOrder.toString().split("-")[1]);
						rotaPerson.setPersonName(rotaOrder.toString().split("-")[2]);
					}else if(rotaPerson.getPersonName()==null || rotaPerson.getPersonName()==null){
						addErrorMessage("未选择值班人，保存失败");
						return;
					}
				
					rotaPersonManager.createRotaPerson(rotaPerson);
					rotaPersons.add(rotaPerson);
				}else{
					addErrorMessage("未选择值班人，保存失败");
					return;
				}
			} else { //编辑
				if(rotaOrder!=null&&rotaOrder.getPersonName()!=null){
					if("".equals(rotaPerson.getRemark())||rotaPerson.getRemark()==null){
						addErrorMessage("未选择节假日，保存失败");
						return;
					}
					if(rotaPerson.getRotaDate()!=null){
						Calendar cal=Calendar.getInstance();
						cal.setTime(rotaPerson.getRotaDate());						
						if(cal.get(cal.MONTH)==11 && "元旦".equals(rotaPerson.getRemark())){
							rotaPerson.setYear(cal.get(cal.YEAR)+1);
						}else{
							rotaPerson.setYear(cal.get(cal.YEAR));
						}
					}else{
						addErrorMessage("未选择日期，保存失败");
						return;
					}
					if(!"null-".equals(rotaOrder.toString())){
						rotaPerson.setPersonId(rotaOrder.toString().split("-")[1]);
						rotaPerson.setPersonName(rotaOrder.toString().split("-")[2]);
					}else if(rotaPerson.getPersonName()==null || rotaPerson.getPersonName()==null){
						addErrorMessage("未选择值班人，保存失败");
						return;
					}
				}
				rotaPersonManager.updateRotaPerson(rotaPerson);
				//selectRotaPerson = new RotaPerson();
			}
			rotaOrder=new RotaOrder();
			addSuccessMessage("保存成功");
		}
	}
	
	public void deleteRotaPerson() {
		if(selectRotaPerson != null) {
			rotaPersonManager.delRotaPerson(selectRotaPerson.getId());
			rotaPersons.remove(selectRotaPerson);
			addSuccessMessage("删除成功！");
		} else {
			addErrorMessage("请选择记录");
		}
		selectRotaPerson = null;
	}

	public void onRotaPersonSelect(SelectEvent event) {
		selectRotaPerson = (RotaPerson)event.getObject();
	}
	
	public void onHolidaySelect(SelectEvent event) {
		selectedHoliday = (HolidayInfo)event.getObject();
	}
	
	public List<HolidayInfo> getHolidays() {
		return holidays;
	}

	public void setHolidays(List<HolidayInfo> holidays) {
		this.holidays = holidays;
	}

	public HolidayInfo getSelectedHoliday() {
		return selectedHoliday;
	}

	public void setSelectedHoliday(HolidayInfo selectedHoliday) {
		this.selectedHoliday = selectedHoliday;
	}

	public HolidayInfo getHoliday() {
		return holiday;
	}

	public void setHoliday(HolidayInfo holiday) {
		this.holiday = holiday;
	}

	public List<String> getHolidayNames() {
		return holidayNames;
	}

	public void setHolidayNames(List<String> holidayNames) {
		this.holidayNames = holidayNames;
	}

	public String getSelectDate() {
		return selectDate;
	}

	public void setSelectDate(String selectDate) {
		this.selectDate = selectDate;
	}

	public List<HolidayInfo> getSelectDateHolidays() {
		return selectDateHolidays;
	}

	public void setSelectDateHolidays(List<HolidayInfo> selectDateHolidays) {
		this.selectDateHolidays = selectDateHolidays;
	}
	
	
	public String getHolidayName() {
		return holidayName;
	}

	public void setHolidayName(String holidayName) {
		this.holidayName = holidayName;
	}

	public Date getHolidayStartDate() {
		return holidayStartDate;
	}

	public void setHolidayStartDate(Date holidayStartDate) {
		this.holidayStartDate = holidayStartDate;
	}

	public Date getHolidayEndDate() {
		return holidayEndDate;
	}

	public void setHolidayEndDate(Date holidayEndDate) {
		this.holidayEndDate = holidayEndDate;
	}

	public String getHolidayRemark() {
		return holidayRemark;
	}

	public void setHolidayRemark(String holidayRemark) {
		this.holidayRemark = holidayRemark;
	}

	public List<RotaPerson> getRotaPersons() {
		return rotaPersons;
	}

	public void setRotaPersons(List<RotaPerson> rotaPersons) {
		this.rotaPersons = rotaPersons;
	}

	public RotaPerson getRotaPerson() {
		return rotaPerson;
	}

	public void setRotaPerson(RotaPerson rotaPerson) {
		this.rotaPerson = rotaPerson;
	}

	public RotaPerson getSelectRotaPerson() {
		return selectRotaPerson;
	}

	public void setSelectRotaPerson(RotaPerson selectRotaPerson) {
		this.selectRotaPerson = selectRotaPerson;
	}

	public List<RotaOrder> getRotaOrders() {
		return rotaOrders;
	}

	public void setRotaOrders(List<RotaOrder> rotaOrders) {
		this.rotaOrders = rotaOrders;
	}

	public RotaOrder getRotaOrder() {
		return rotaOrder;
	}

	public void setRotaOrder(RotaOrder rotaOrder) {
		this.rotaOrder = rotaOrder;
	}

	public HolidayInfo getSelectDateHoliday() {
		return selectDateHoliday;
	}

	public void setSelectDateHoliday(HolidayInfo selectDateHoliday) {
		this.selectDateHoliday = selectDateHoliday;
	}

	public String getRotaPersonIdAndName() {
		return rotaPersonIdAndName;
	}

	public void setRotaPersonIdAndName(String rotaPersonIdAndName) {
		this.rotaPersonIdAndName = rotaPersonIdAndName;
	}


}
